import getExtraData from "./getExtraData";

const host = 'cn-chengdu.log.aliyuncs.com';
const project = 'monitor-test001';
const logStore = 'monitor-test001--store';

class SendTracker {
  constructor() {
    this.url = `https://${project}.${host}/logstores/${logStore}/track`; //上报路径
    this.xhr = new XMLHttpRequest();
  }

  send(data = {}){
    const extraData = getExtraData();
    const log = {...data, ...extraData};
    this.xhr.open('POST', this.url, true);

    //阿里云要求上传的对象里的值不能是数字
    //否则会报: Value in log is not string data type
    for (const key in log) {
      if (typeof log[key] === 'number') {
        log[key] = `${log[key]}`;
      }
    }

    console.log('send log:',log);

    //https://help.aliyun.com/document_detail/120218.html?spm=a2c4g.11186623.6.1323.9b5939f13vynzX
    const body = JSON.stringify({
      __logs__: [log]
    });

    this.xhr.setRequestHeader('Content-Type', 'application/json');
    this.xhr.setRequestHeader('x-log-apiversion', '0.6.0');
    this.xhr.setRequestHeader('x-log-bodyrawsize', body.length);

    this.xhr.send(body);

    this.xhr.onload = function(){

    }
    this.xhr.onerror = function(error){

    }
  }
}

export default new SendTracker();
